// 文件系统状态管理

import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { 
  FileItem, 
  WorkspaceInfo, 
  FileTreeNode, 
  FileOperation, 
  FileOperationHistory,
  FileSystemState,
  buildFileTree 
} from '../types/filesystem';
import { FileSystemService } from '../services/filesystem';

interface FileSystemStore extends FileSystemState {
  // 状态
  isLoading: boolean;
  error: string | null;
  operationHistory: FileOperationHistory;

  // 操作
  setWorkspace: (workspace: WorkspaceInfo) => void;
  loadDirectory: (path: string) => Promise<void>;
  refreshDirectory: () => Promise<void>;
  selectFile: (path: string, isMultiSelect?: boolean) => void;
  selectFiles: (paths: string[]) => void;
  clearSelection: () => void;
  toggleDirectory: (path: string) => void;
  setSearchQuery: (query: string) => void;
  
  // 文件操作
  createFile: (path: string) => Promise<boolean>;
  createDirectory: (path: string) => Promise<boolean>;
  deleteFile: (path: string) => Promise<boolean>;
  renameFile: (oldPath: string, newPath: string) => Promise<boolean>;
  moveFile: (oldPath: string, newPath: string) => Promise<boolean>;
  
  // 撤销/重做
  undo: () => Promise<void>;
  redo: () => Promise<void>;
  canUndo: () => boolean;
  canRedo: () => boolean;
  
  // 工具方法
  getSelectedFiles: () => FileItem[];
  findFileByPath: (path: string) => FileItem | undefined;
  isDirectoryExpanded: (path: string) => boolean;
  isFileSelected: (path: string) => boolean;
}

export const useFileSystemStore = create<FileSystemStore>()(
  subscribeWithSelector((set, get) => ({
    // 初始状态
    currentWorkspace: undefined,
    selectedFiles: [],
    expandedDirectories: new Set(),
    searchQuery: '',
    filteredFiles: [],
    fileTree: [],
    isLoading: false,
    error: null,
    operationHistory: {
      operations: [],
      currentIndex: -1,
    },

    // 设置工作区
    setWorkspace: (workspace) => {
      set({
        currentWorkspace: workspace,
        fileTree: buildFileTree(workspace.files, workspace.path),
        selectedFiles: [],
        expandedDirectories: new Set(),
        searchQuery: '',
        error: null,
      });
    },

    // 加载目录
    loadDirectory: async (path) => {
      console.log('FileSystemStore: Loading directory:', path);
      set({ isLoading: true, error: null });

      try {
        const workspaceInfo = await FileSystemService.getWorkspaceInfo(path);
        console.log('FileSystemStore: Workspace info loaded:', workspaceInfo);
        get().setWorkspace(workspaceInfo);
      } catch (error) {
        console.error('FileSystemStore: Failed to load directory:', error);
        const errorMessage = error instanceof Error ? error.message : 'Failed to load directory';
        set({
          error: errorMessage,
          isLoading: false
        });
      } finally {
        set({ isLoading: false });
      }
    },

    // 刷新目录
    refreshDirectory: async () => {
      const { currentWorkspace } = get();
      if (currentWorkspace) {
        await get().loadDirectory(currentWorkspace.path);
      }
    },

    // 选择文件
    selectFile: (path, isMultiSelect = false) => {
      const { selectedFiles } = get();
      
      if (isMultiSelect) {
        const newSelection = selectedFiles.includes(path)
          ? selectedFiles.filter(p => p !== path)
          : [...selectedFiles, path];
        set({ selectedFiles: newSelection });
      } else {
        set({ selectedFiles: [path] });
      }
    },

    // 选择多个文件
    selectFiles: (paths) => {
      set({ selectedFiles: paths });
    },

    // 清除选择
    clearSelection: () => {
      set({ selectedFiles: [] });
    },

    // 切换目录展开状态
    toggleDirectory: (path) => {
      const { expandedDirectories } = get();
      const newExpanded = new Set(expandedDirectories);
      
      if (expandedDirectories.has(path)) {
        newExpanded.delete(path);
      } else {
        newExpanded.add(path);
      }
      
      set({ expandedDirectories: newExpanded });
    },

    // 设置搜索查询
    setSearchQuery: (query) => {
      set({ searchQuery: query });
      // TODO: 实现搜索过滤逻辑
    },

    // 创建文件
    createFile: async (path) => {
      try {
        const result = await FileSystemService.createFile(path);
        
        if (result.success) {
          // 记录操作历史
          const operation: FileOperation = {
            type: 'create',
            path,
            isDirectory: false,
            timestamp: Date.now(),
          };
          
          const { operationHistory } = get();
          const newHistory = {
            operations: [
              ...operationHistory.operations.slice(0, operationHistory.currentIndex + 1),
              operation,
            ],
            currentIndex: operationHistory.currentIndex + 1,
          };
          
          set({ operationHistory: newHistory });
          
          // 刷新目录
          await get().refreshDirectory();
          return true;
        } else {
          set({ error: result.message });
          return false;
        }
      } catch (error) {
        set({ error: error instanceof Error ? error.message : 'Failed to create file' });
        return false;
      }
    },

    // 创建目录
    createDirectory: async (path) => {
      try {
        const result = await FileSystemService.createDirectory(path);
        
        if (result.success) {
          const operation: FileOperation = {
            type: 'create',
            path,
            isDirectory: true,
            timestamp: Date.now(),
          };
          
          const { operationHistory } = get();
          const newHistory = {
            operations: [
              ...operationHistory.operations.slice(0, operationHistory.currentIndex + 1),
              operation,
            ],
            currentIndex: operationHistory.currentIndex + 1,
          };
          
          set({ operationHistory: newHistory });
          await get().refreshDirectory();
          return true;
        } else {
          set({ error: result.message });
          return false;
        }
      } catch (error) {
        set({ error: error instanceof Error ? error.message : 'Failed to create directory' });
        return false;
      }
    },

    // 删除文件
    deleteFile: async (path) => {
      try {
        const result = await FileSystemService.deleteFileOrDirectory(path);
        
        if (result.success) {
          const file = get().findFileByPath(path);
          const operation: FileOperation = {
            type: 'delete',
            path,
            isDirectory: file?.is_directory || false,
            timestamp: Date.now(),
          };
          
          const { operationHistory } = get();
          const newHistory = {
            operations: [
              ...operationHistory.operations.slice(0, operationHistory.currentIndex + 1),
              operation,
            ],
            currentIndex: operationHistory.currentIndex + 1,
          };
          
          set({ operationHistory: newHistory });
          await get().refreshDirectory();
          return true;
        } else {
          set({ error: result.message });
          return false;
        }
      } catch (error) {
        set({ error: error instanceof Error ? error.message : 'Failed to delete file' });
        return false;
      }
    },

    // 重命名文件
    renameFile: async (oldPath, newPath) => {
      try {
        const result = await FileSystemService.renameFileOrDirectory(oldPath, newPath);
        
        if (result.success) {
          const file = get().findFileByPath(oldPath);
          const operation: FileOperation = {
            type: 'rename',
            path: oldPath,
            newPath,
            isDirectory: file?.is_directory || false,
            timestamp: Date.now(),
          };
          
          const { operationHistory } = get();
          const newHistory = {
            operations: [
              ...operationHistory.operations.slice(0, operationHistory.currentIndex + 1),
              operation,
            ],
            currentIndex: operationHistory.currentIndex + 1,
          };
          
          set({ operationHistory: newHistory });
          await get().refreshDirectory();
          return true;
        } else {
          set({ error: result.message });
          return false;
        }
      } catch (error) {
        set({ error: error instanceof Error ? error.message : 'Failed to rename file' });
        return false;
      }
    },

    // 移动文件
    moveFile: async (oldPath, newPath) => {
      return get().renameFile(oldPath, newPath);
    },

    // 撤销操作
    undo: async () => {
      const { operationHistory } = get();
      
      if (!get().canUndo()) return;
      
      const operation = operationHistory.operations[operationHistory.currentIndex];
      
      try {
        // 执行反向操作
        switch (operation.type) {
          case 'create':
            await FileSystemService.deleteFileOrDirectory(operation.path);
            break;
          case 'delete':
            // 删除操作的撤销比较复杂，这里简化处理
            console.warn('Undo delete operation is not fully implemented');
            break;
          case 'rename':
            if (operation.newPath) {
              await FileSystemService.renameFileOrDirectory(operation.newPath, operation.path);
            }
            break;
        }
        
        set({
          operationHistory: {
            ...operationHistory,
            currentIndex: operationHistory.currentIndex - 1,
          }
        });
        
        await get().refreshDirectory();
      } catch (error) {
        set({ error: error instanceof Error ? error.message : 'Failed to undo operation' });
      }
    },

    // 重做操作
    redo: async () => {
      const { operationHistory } = get();
      
      if (!get().canRedo()) return;
      
      const operation = operationHistory.operations[operationHistory.currentIndex + 1];
      
      try {
        // 重新执行操作
        switch (operation.type) {
          case 'create':
            if (operation.isDirectory) {
              await FileSystemService.createDirectory(operation.path);
            } else {
              await FileSystemService.createFile(operation.path);
            }
            break;
          case 'delete':
            await FileSystemService.deleteFileOrDirectory(operation.path);
            break;
          case 'rename':
            if (operation.newPath) {
              await FileSystemService.renameFileOrDirectory(operation.path, operation.newPath);
            }
            break;
        }
        
        set({
          operationHistory: {
            ...operationHistory,
            currentIndex: operationHistory.currentIndex + 1,
          }
        });
        
        await get().refreshDirectory();
      } catch (error) {
        set({ error: error instanceof Error ? error.message : 'Failed to redo operation' });
      }
    },

    // 检查是否可以撤销
    canUndo: () => {
      const { operationHistory } = get();
      return operationHistory.currentIndex >= 0;
    },

    // 检查是否可以重做
    canRedo: () => {
      const { operationHistory } = get();
      return operationHistory.currentIndex < operationHistory.operations.length - 1;
    },

    // 获取选中的文件
    getSelectedFiles: () => {
      const { selectedFiles, currentWorkspace } = get();
      if (!currentWorkspace) return [];
      
      return currentWorkspace.files.filter(file => 
        selectedFiles.includes(file.path)
      );
    },

    // 根据路径查找文件
    findFileByPath: (path) => {
      const { currentWorkspace } = get();
      if (!currentWorkspace) return undefined;
      
      return currentWorkspace.files.find(file => file.path === path);
    },

    // 检查目录是否展开
    isDirectoryExpanded: (path) => {
      const { expandedDirectories } = get();
      return expandedDirectories.has(path);
    },

    // 检查文件是否选中
    isFileSelected: (path) => {
      const { selectedFiles } = get();
      return selectedFiles.includes(path);
    },
  }))
);
